package com.putao.album.user;

import android.content.IntentFilter;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.user.util.FlowType;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/22.
 */
public class ActivityInputVCode extends BaseActivity {
    private String telnum;
    private int mflowtype = 0;
    private EditText etx_vcode, txt_mobile_display;
    private Button btn_request_vcode, btn_next, btn_back, btn_edit_mobile, btn_delete_vcode;
    private SMSBroadcastReceiver mSMSBroadcastReceiver;
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_input_vcode;
    }

    @Override
    public void doInitSubViews(View view) {
        etx_vcode = queryViewById(R.id.etx_vcode);
        txt_mobile_display = queryViewById(R.id.txt_mobile_display);
        btn_request_vcode = queryViewById(R.id.btn_request_vcode);
        btn_next = queryViewById(R.id.btn_next);
        btn_back = queryViewById(R.id.btn_back);
        btn_edit_mobile = queryViewById(R.id.btn_edit_mobile);
        btn_delete_vcode = queryViewById(R.id.btn_delete_vcode);
        addOnClickListener(btn_next, btn_request_vcode, btn_back, btn_edit_mobile, btn_delete_vcode);
        etx_vcode.addTextChangedListener(mVcodeTextWatch);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerSMSBroadcast();
    }

    private void registerSMSBroadcast() {
        mSMSBroadcastReceiver = new SMSBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(ACTION);
        intentFilter.setPriority(Integer.MAX_VALUE);
        this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            @Override
            public void onReceived(String message) {
                if (!StringHelper.isEmpty(message)) {
                    int start_index = firstIndexOf(message, '：');
                    int end_index = firstIndexOf(message, '，');
                    if (start_index > 0 && end_index > 0) {
                        String code = message.substring(start_index + 1, end_index);
                        etx_vcode.setText(code);
                    }
                }
            }
        });
    }

    int firstIndexOf(String str, char c) {
        char[] cs = str.toCharArray();
        for (int i = 0; i < str.length(); i++) {
            if (c == cs[i]) {
                return i;
            }
        }
        return -1;
    }


    TextWatcher mVcodeTextWatch = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String tex = etx_vcode.getText().toString();
            if (!StringHelper.isEmpty(tex)) {
                btn_delete_vcode.setVisibility(View.VISIBLE);
                btn_next.setEnabled(true);
                btn_next.setAlpha(1f);
            } else {
                btn_delete_vcode.setVisibility(View.GONE);
                btn_next.setEnabled(false);
                btn_next.setAlpha(.5f);
            }
        }
    };

    @Override
    public void doInitData() {
        if (getIntent() != null) {
            Bundle receiveBundle = getIntent().getExtras();
            if (receiveBundle != null) {
                telnum = receiveBundle.getString(FlowType.flag_mobile);
                mflowtype = receiveBundle.getInt(FlowType.flag_flowtype, 0);
            }
        }
        txt_mobile_display.setText(telnum);
        if (mflowtype == FlowType.flow_modify_pwd) {
            btn_edit_mobile.setVisibility(View.VISIBLE);
        }
        if (!StringHelper.isEmpty(telnum) && mflowtype != FlowType.flow_modify_pwd) {
            requestVCode();
        }
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_LOGIN_SUCCESS:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        this.unregisterReceiver(mSMSBroadcastReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                doValidationCode();
                break;
            case R.id.btn_request_vcode:
                requestVCode();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_edit_mobile:
                txt_mobile_display.setEnabled(true);
                txt_mobile_display.setSelection(txt_mobile_display.getText().length());
                txt_mobile_display.setBackgroundDrawable(getResources().getDrawable(R.drawable.login_vcode_tel_edit_bg));
                btn_edit_mobile.setVisibility(View.GONE);
                break;
            case R.id.btn_delete_vcode:
                etx_vcode.setText("");
                break;
        }
    }

    void doValidationCode() {
        if (!checkTelNum()) {
            return;
        }
        String vcode = etx_vcode.getText().toString();
        if (StringHelper.isEmpty(vcode)) {
            showToast("请输入验证码");
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("mobile", telnum);
        params.put("vcode", vcode);
        if (mflowtype == FlowType.flow_register) {
            params.put("action", "reg");
        } else if (mflowtype == FlowType.flow_modify_pwd) {
            params.put("action", "edit_pwd");
        }

        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_MOBILE_BIND, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {//验证成功
                        Bundle bundle = new Bundle();
                        bundle.putString(FlowType.flag_mobile, telnum);
                        bundle.putInt(FlowType.flag_flowtype, mflowtype);
                        ActivityHelper.startActivity(mActivity, ActivityInputPassword.class, bundle);
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    public class RequestCodeWaitTask extends Thread {
        int count = 60;

        @Override
        public void run() {
            super.run();
            while (count > -1) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String send_string = getResources().getString(R.string.btn_resend_vcode);
                        btn_request_vcode.setTextColor(getResources().getColor(R.color.color_middle_grey));
                        btn_request_vcode.setText(Html.fromHtml(send_string + " <font color='" + getResources().getColor(R.color.color_main) + "'>" + count + "</font> "));
                        if (count <= 0) {
                            btn_request_vcode.setEnabled(true);
                            btn_request_vcode.setTextColor(getResources().getColor(R.color.color_main));
                            btn_request_vcode.setText(getResources().getString(R.string.btn_send_vcode));
                        }
                    }
                });
                count--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    boolean checkTelNum() {
        telnum = txt_mobile_display.getText().toString();
        if (!StringHelper.checkMobileFormat(telnum)) {
            showToast("这不是手机号码哦，再试一下吧");
            return false;
        }
        return true;
    }

    /**
     * 请求注册短信验证码
     */
    void requestVCode() {
        if (!checkTelNum()) {
            return;
        }
        MobclickAgent.onEvent(mContext, UmengTouchEvent.CLICK_CAPTCHA);
        btn_request_vcode.setEnabled(false);
        new RequestCodeWaitTask().start();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("mobile", telnum);
        if (mflowtype == FlowType.flow_register) {
            params.put("action", "reg");
        } else if (mflowtype == FlowType.flow_modify_pwd) {
            params.put("action", "edit_pwd");
        }
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_MOBILE_VCODE, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                Loger.d("response:" + response);
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {//请求成功
                        showToast("验证码已发送，请注意查收！");
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            JSONObject data = json.getJSONObject("data");
//                            if (data != null) {
//                                String msg = data.getString("msg");
//                                if (!StringHelper.isEmpty(msg)) {
//                                    msg = msg.replace("验证码:", "");
//                                    etx_vcode.setText(msg);
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                showToast(response);
            }
        });
    }
}
